<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import PaginationCommon from '@/components/PaginationCommon.vue'
import RoleService from '@/api/services/RoleService'

// 角色数据类型定义
interface Role {
  id: number
  roleName: string
  roleDesc: string
  status: 1 | 0 // 状态：0-禁用，1-启用
  createTime: string
  updateTime: string
}

// 响应数据
const roleList = ref<Role[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentRoleId = ref<number | null>(null)
const selectedRoles = ref<number[]>([])

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表单数据
const form = reactive({
  id: 0,
  roleName: '',
  roleDesc: '',
  status: 1 as 1 | 0
})

// 表单引用
const formRef = ref<FormInstance>()

// 表单验证规则
const rules = reactive<FormRules>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
})

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
]

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true
  try {
    // 调用RoleService的getRolePagedListAsync方法
    const result = await RoleService.getRolePagedListAsync({
      roleName: searchForm.roleName,
      status: searchForm.status,
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    })

    if (result.success) {
      // 更新角色列表和分页数据 - 使用类型断言将unknown[]转换为Role[]
      roleList.value = result.data.data as Role[]
      total.value = result.data.totalCount
      currentPage.value = result.data.pageIndex
      pageSize.value = result.data.pageSize
    } else {
      ElMessage.error(`获取角色列表失败: ${result.message}`)
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 分页变化处理
const handlePageChange = (page: number, size: number) => {
  currentPage.value = page
  pageSize.value = size
  fetchRoles()
}

// 打开添加角色对话框
const openAddDialog = () => {
  dialogTitle.value = '添加角色'
  isEdit.value = false
  currentRoleId.value = null

  // 重置表单
  Object.assign(form, {
    id: 0,
    roleName: '',
    roleDesc: '',
    status: 1
  })

  dialogVisible.value = true
}

// 打开编辑角色对话框
const openEditDialog = (role: Role) => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  currentRoleId.value = role.id
  // 填充表单数据
  Object.assign(form, {
    id: role.id,
    roleName: role.roleName,
    roleDesc: role.roleDesc,
    status: role.status
  })

  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value && form.id) {
          // 更新角色
          const updateParams = {
            id: form.id,
            roleName: form.roleName,
            roleDesc: form.roleDesc,
            status: form.status
          }
          const result = await RoleService.updateRoleAsync(updateParams)

          if (result.success) {
            ElMessage.success('角色更新成功')
            dialogVisible.value = false
            fetchRoles() // 刷新列表
          } else {
            ElMessage.error(`更新角色失败: ${result.message}`)
          }
        } else {
          // 添加角色
          const addParams = {
            roleName: form.roleName,
            roleDesc: form.roleDesc
          }
          const result = await RoleService.addRoleAsync(addParams)

          if (result.success) {
            ElMessage.success('角色添加成功')
            dialogVisible.value = false
            fetchRoles() // 刷新列表
          } else {
            ElMessage.error(`添加角色失败: ${result.message}`)
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(isEdit.value ? '更新角色失败' : '添加角色失败')
      }
    }
  })
}

// 用户数据类型定义
interface User {
  id: number
  realname: string
  account: string
  phone?: string | null
  email?: string | null
  status: number
  createTime: string
  updateTime: string
}

// 绑定用户数据类型
interface BandUser {
  id: number
  account: string
  password: string
  realname: string
  phone?: string | null
  email?: string | null
  status: number
  createTime: string
  updateTime: string
}

// 角色用户信息响应数据类型
interface RoleUserInfoResponse {
  noBandUsers: User[]
  bandUsers: BandUser[]
}

// 绑定相关数据
const bandDialogVisible = ref(false)
const selectedUserIds = ref<number[]>([])
const userOptions = ref<{ key: number; label: string }[]>([])

const currentRole = ref<Role | null>(null)
const noBandUsers = ref<User[]>([])
const bandUsers = ref<BandUser[]>([])

// 菜单绑定相关数据
const menuBindDialogVisible = ref(false)
const menuTreeData = ref<MenuTreeNode[]>([])
const selectedMenuIds = ref<number[]>([])

// 打开绑定对话框
const openUsersBindDialog = async (role: Role) => {
  currentRole.value = role
  bandDialogVisible.value = true
  selectedUserIds.value = []

  // 获取该角色已绑定的用户信息
  await fetchRoleUserInfo(role.id)
}

// 菜单树数据类型定义
interface MenuTreeNode {
  id: number
  menuName: string
  isBand: boolean
  children: MenuTreeNode[]
}

const openMuensBindDialog = async (role: Role) => {
  currentRole.value = role
  menuBindDialogVisible.value = true
  selectedMenuIds.value = []

  // 获取菜单树数据
  await fetchMenuTreeWithRoleStatus(role.id)
}

// 获取菜单树数据
const fetchMenuTreeWithRoleStatus = async (roleId: number) => {
  try {
    const params = {
      roleId: roleId
    }
    const result = await RoleService.getMenuTreeWithRoleStatusAsync(params)
    if (result.success) {
      const data = result.data as MenuTreeNode[]
      menuTreeData.value = data || []

      // 设置已选中的菜单ID（已绑定的菜单）
      selectedMenuIds.value = getSelectedMenuIds(data)
    } else {
      ElMessage.error(`获取菜单树数据失败: ${result.message}`)
    }
  } catch (error) {
    console.error('获取菜单树数据失败:', error)
    ElMessage.error('获取菜单树数据失败')
  }
}

// 递归获取所有已绑定的菜单ID
const getSelectedMenuIds = (menuNodes: MenuTreeNode[]): number[] => {
  const selectedIds: number[] = []

  const traverse = (nodes: MenuTreeNode[]) => {
    nodes.forEach(node => {
      if (node.isBand) {
        selectedIds.push(node.id)
      }
      if (node.children && node.children.length > 0) {
        traverse(node.children)
      }
    })
  }

  traverse(menuNodes)
  return selectedIds
}

// 处理菜单选择变化
// const handleMenuSelectionChange = (selectedIds: number[]) => {
//   selectedMenuIds.value = selectedIds
// }

// 处理复选框变化
const handleCheckboxChange = (menuData: MenuTreeNode) => {
  const menuId = menuData.id
  if (menuData.isBand) {
    // 如果选中，添加到选中列表
    if (!selectedMenuIds.value.includes(menuId)) {
      selectedMenuIds.value.push(menuId)
    }

    // 如果勾选的是一级菜单，自动勾选其所有二级菜单
    if (menuData.children && menuData.children.length > 0) {
      // 这是一个父节点（一级菜单），需要勾选所有子节点
      const selectAllChildren = (nodes: MenuTreeNode[]) => {
        nodes.forEach(child => {
          if (!child.isBand) {
            child.isBand = true
            if (!selectedMenuIds.value.includes(child.id)) {
              selectedMenuIds.value.push(child.id)
            }
          }
          // 递归处理子节点的子节点（如果有更深层级）
          if (child.children && child.children.length > 0) {
            selectAllChildren(child.children)
          }
        })
      }
      selectAllChildren(menuData.children)
    }

    // 如果勾选的是二级菜单，自动勾选其一级菜单
    if (menuData.children && menuData.children.length === 0) {
      // 这是一个叶子节点（二级菜单），需要找到其父节点并勾选
      const parentNode = findParentNode(menuTreeData.value, menuId)
      if (parentNode && !parentNode.isBand) {
        parentNode.isBand = true
        if (!selectedMenuIds.value.includes(parentNode.id)) {
          selectedMenuIds.value.push(parentNode.id)
        }
      }
    }
  } else {
    // 如果取消选中，从选中列表中移除
    const index = selectedMenuIds.value.indexOf(menuId)
    if (index > -1) {
      selectedMenuIds.value.splice(index, 1)
    }

    // 如果取消勾选的是一级菜单，自动取消勾选其所有二级菜单
    if (menuData.children && menuData.children.length > 0) {
      // 这是一个父节点（一级菜单），需要取消勾选所有子节点
      const unselectAllChildren = (nodes: MenuTreeNode[]) => {
        nodes.forEach(child => {
          if (child.isBand) {
            child.isBand = false
            const childIndex = selectedMenuIds.value.indexOf(child.id)
            if (childIndex > -1) {
              selectedMenuIds.value.splice(childIndex, 1)
            }
          }
          // 递归处理子节点的子节点（如果有更深层级）
          if (child.children && child.children.length > 0) {
            unselectAllChildren(child.children)
          }
        })
      }
      unselectAllChildren(menuData.children)
    }
  }
}

// 递归查找父节点
const findParentNode = (nodes: MenuTreeNode[], targetId: number): MenuTreeNode | null => {
  for (const node of nodes) {
    if (node.children && node.children.length > 0) {
      // 检查当前节点的子节点是否包含目标节点
      const foundInChildren = node.children.some(child => child.id === targetId)
      if (foundInChildren) {
        return node
      }

      // 递归查找子节点
      const found = findParentNode(node.children, targetId)
      if (found) {
        return found
      }
    }
  }
  return null
}

// 绑定菜单
const bindMenus = async () => {
  if (!currentRole.value) {
    ElMessage.warning('请选择角色')
    return
  }

  try {
    // 返回包含选中菜单ID和角色ID的对象
    const bindResult = {
      menuIds: selectedMenuIds.value,
      roleId: currentRole.value.id
    }

    const data = RoleService.isBindMenuAsync(bindResult);
    if ((await data).success) {
      ElMessage.success((await data).message)
    } else {
      ElMessage.error((await data).message)
    }


    menuBindDialogVisible.value = false

    // 返回绑定结果对象
    return bindResult
  } catch (error) {
    console.error('绑定菜单失败:', error)
    ElMessage.error('绑定菜单失败')
  }
}

// 菜单绑定对话框关闭处理
const handleMenuBindDialogClose = () => {
  selectedMenuIds.value = []
  currentRole.value = null
  menuTreeData.value = []
}

// 获取角色用户信息
const fetchRoleUserInfo = async (roleId: number) => {
  try {
    const result = await RoleService.getUserRoleInfoAsync(roleId)
    if (result.success) {
      const data = result.data as RoleUserInfoResponse
      noBandUsers.value = data.noBandUsers || []
      bandUsers.value = data.bandUsers || []

      // 初始化用户选项
      initUserOptions(data.noBandUsers, data.bandUsers)

      // 设置已选中的用户ID（已绑定的用户）
      selectedUserIds.value = data.bandUsers.map(user => user.id)
    } else {
      ElMessage.error(`获取角色用户信息失败: ${result.message}`)
    }
  } catch (error) {
    console.error('获取角色用户信息失败:', error)
    ElMessage.error('获取角色用户信息失败')
  }
}

// 初始化用户选项
const initUserOptions = (noBandUsers: User[], bandUsers: BandUser[]) => {
  try {
    // 创建所有用户的映射
    const allUsersMap = new Map<number, User>()
    noBandUsers.forEach(user => {
      allUsersMap.set(user.id, user)
    })

    // 创建完整的用户选项列表
    const allUserOptions: { key: number; label: string }[] = []

    // 添加未绑定用户
    noBandUsers.forEach(user => {
      allUserOptions.push({
        key: user.id,
        label: user.realname
      })
    })


    // 添加已绑定用户（如果不在未绑定用户列表中）
    bandUsers.forEach(bandUser => {
      const user = allUsersMap.get(bandUser.id)
      if (user) {
        // 用户已经在未绑定用户列表中，不需要重复添加
        // 穿梭框会自动处理显示
      } else {
        // 如果已绑定用户不在未绑定用户列表中，需要添加
        // 使用已绑定用户的真实姓名
        allUserOptions.push({
          key: bandUser.id,
          label: bandUser.realname
        })
      }
    })

    userOptions.value = allUserOptions
  } catch (error) {
    console.error('初始化用户选项失败:', error)
    ElMessage.error('初始化用户选项失败')
  }
}

// 过滤方法
const filterMethod = (query: string, item: { key: number; label: string }) => {
  return item.label.toLowerCase().includes(query.toLowerCase())
}

// 穿梭框变化处理
const handleTransferChange = async (value: number[], direction: 'left' | 'right', movedKeys: number[]) => {
  if (!currentRole.value) {
    ElMessage.warning('请选择角色')
    return
  }

  try {
    if (direction === 'right') {
      // 绑定操作 - 从左侧移动到右侧
      console.log('执行绑定操作')
      const bindParams = {
        isBand: 1, // 1表示绑定
        roleId: currentRole.value.id,
        userIds: movedKeys
      }
      const bindResult = await RoleService.isBandUserAsync(bindParams)
      if (bindResult.success) {
        ElMessage.success('绑定成功')
        // 更新本地数据
        await fetchRoleUserInfo(currentRole.value.id)
      } else {
        ElMessage.error(`绑定失败: ${bindResult.message}`)
      }
    } else if (direction === 'left') {
      // 解绑操作 - 从右侧移动到左侧
      console.log('执行解绑操作')
      const unbindParams = {
        isBand: 0, // 0表示解绑
        roleId: currentRole.value.id,
        userIds: movedKeys
      }
      const unbindResult = await RoleService.isBandUserAsync(unbindParams)
      if (unbindResult.success) {
        ElMessage.success('解绑成功')
        // 更新本地数据
        await fetchRoleUserInfo(currentRole.value.id)
      } else {
        ElMessage.error(`解绑失败: ${unbindResult.message}`)
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 对话框关闭处理
const handleDialogClose = () => {
  selectedUserIds.value = []
  currentRole.value = null
}

// 切换角色状态
const toggleStatus = async (role: Role) => {
  try {
    const newStatus = role.status === 1 ? 0 : 1
    const action = newStatus === 1 ? '启用' : '禁用'

    await ElMessageBox.confirm(
      `确定要${action}角色 "${role.roleName}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用RoleService的单个角色状态更新方法
    const result = await RoleService.updateRoleStatusAsync(role.id)

    if (result.success) {
      // 更新本地数据状态
      const index = roleList.value.findIndex(r => r.id === role.id)
      if (index !== -1) {
        roleList.value[index]!.status = newStatus
        roleList.value[index]!.updateTime = new Date().toLocaleString('zh-CN')
      }
      ElMessage.success(`角色${action}成功`)
    } else {
      ElMessage.error(`角色${action}失败: ${result.message}`)
    }
  } catch {
    // 用户取消操作
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

// 搜索相关数据
const searchForm = reactive({
  roleName: '',
  status: 1 as 1 | 0 | ''
})

// 搜索角色
const searchRoles = () => {
  // 重置到第一页进行搜索
  currentPage.value = 1
  fetchRoles()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    roleName: '',
    status: 1
  })
  fetchRoles()
}

// 批量启用角色
const batchEnableRoles = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要启用的角色')
    return
  }

  try {
    const selectedNames = roleList.value
      .filter(role => selectedRoles.value.includes(role.id))
      .map(role => role.roleName)
      .join('、')

    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedRoles.value.length} 个角色吗？\n${selectedNames}`,
      '批量启用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用RoleService的批量状态更新方法
    const result = await RoleService.updateRolesStatusAsync(selectedRoles.value)

    if (result.success) {
      // 更新本地数据状态
      selectedRoles.value.forEach(roleId => {
        const role = roleList.value.find(r => r.id === roleId)
        if (role) {
          role.status = 1
          role.updateTime = new Date().toLocaleString('zh-CN')
        }
      })
      ElMessage.success('批量启用成功')
      selectedRoles.value = []
    } else {
      ElMessage.error(`批量启用失败: ${result.message}`)
    }
  } catch {
    // 用户取消操作
  }
}

// 批量禁用角色
const batchDisableRoles = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要禁用的角色')
    return
  }

  try {
    const selectedNames = roleList.value
      .filter(role => selectedRoles.value.includes(role.id))
      .map(role => role.roleName)
      .join('、')

    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedRoles.value.length} 个角色吗？\n${selectedNames}`,
      '批量禁用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用RoleService的批量状态更新方法
    const result = await RoleService.updateRolesStatusAsync(selectedRoles.value)

    if (result.success) {
      // 更新本地数据状态
      selectedRoles.value.forEach(roleId => {
        const role = roleList.value.find(r => r.id === roleId)
        if (role) {
          role.status = 0
          role.updateTime = new Date().toLocaleString('zh-CN')
        }
      })
      ElMessage.success('批量禁用成功')
      selectedRoles.value = []
    } else {
      ElMessage.error(`批量禁用失败: ${result.message}`)
    }
  } catch {
    // 用户取消操作
  }
}

//时间转换
const formatDate = (dateString: string | number | Date) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toISOString().split('T')[0]; // 格式：YYYY-MM-DD
}

// 页面加载时获取角色列表
onMounted(() => {
  fetchRoles()
})
</script>

<template>
  <div class="role-container">

    <!-- 搜索栏 - 单行布局 -->
    <el-card class="search-card">
      <div class="search-bar">
        <el-form :model="searchForm" label-width="auto" class="search-form">
          <div class="search-row">
            <el-form-item label="角色名称">
              <el-input v-model="searchForm.roleName" placeholder="角色名称" clearable style="width: 140px" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="状态" clearable style="width: 120px">
                <el-option label="全部" value="" />
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
            <div class="search-actions">
              <el-button type="primary" @click="searchRoles" size="small">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </el-button>
              <el-button @click="resetSearch" size="small">
                <el-icon>
                  <Refresh />
                </el-icon>
                重置
              </el-button>
            </div>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 角色列表 -->
    <div class="table-container">
      <el-card class="content-card">
        <template #header>
          <div class="table-header">
            <span>角色列表</span>
            <div class="header-actions">
              <el-button type="primary" @click="openAddDialog">
                <el-icon>
                  <Plus />
                </el-icon>
                添加角色
              </el-button>
              <el-button type="success" @click="batchEnableRoles" :disabled="selectedRoles.length === 0">
                批量启用
              </el-button>
              <el-button type="warning" @click="batchDisableRoles" :disabled="selectedRoles.length === 0">
                批量禁用
              </el-button>
              <el-button @click="fetchRoles">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <div class="table-wrapper">
          <el-table :data="roleList" v-loading="loading" style="width: 100%" stripe
            @selection-change="(selection: Role[]) => selectedRoles = selection.map(role => role.id)">

            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column prop="id" label="ID" width="80" fixed="left" align="center" />

            <el-table-column prop="roleName" label="角色名称" min-width="90" show-overflow-tooltip />
            <el-table-column prop="roleDesc" label="角色描述" min-width="90" show-overflow-tooltip />

            <el-table-column prop="status" label="状态" width="90" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="创建时间" width="140" align="center">
              <template #default="{ row }">
                {{ formatDate(row.createTime) }}
              </template>
            </el-table-column>

            <el-table-column prop="updateTime" label="更新时间" width="140" align="center">
              <template #default="{ row }">
                {{ formatDate(row.updateTime) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="320" fixed="right" align="center">
              <template #default="{ row }">
                <el-button size="small" @click="openEditDialog(row)">
                  编辑
                </el-button>
                <el-button size="small" :type="row.status === 1 ? 'warning' : 'success'" @click="toggleStatus(row)">
                  {{ row.status === 1 ? '禁用' : '启用' }}
                </el-button>
                <el-button size="small" @click="openUsersBindDialog(row)" type="primary">
                  绑定用户
                </el-button>
                <el-button size="small" @click="openMuensBindDialog(row)" type="primary">
                  绑定菜单
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 分页组件 - 固定在底部 -->
      <div class="pagination-container">
        <PaginationCommon v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          @page-change="handlePageChange" />
      </div>
    </div>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="form.roleDesc" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>

        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in statusOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 绑定角色对话框 -->
    <el-dialog v-model="bandDialogVisible" :title="`为角色 ${currentRole?.roleName} 绑定用户`" width="800px"
      @close="handleDialogClose">
      <!-- 穿梭框 -->
      <el-transfer v-model="selectedUserIds" :data="userOptions" :titles="['未绑定用户', '已绑定用户']"
        :button-texts="['解绑', '绑定']" filterable :filter-method="filterMethod" @change="handleTransferChange">
        <template #default="{ option }">
          <span>{{ option.label }}</span>
        </template>
      </el-transfer>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bandDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 绑定菜单对话框 -->
    <el-dialog v-model="menuBindDialogVisible" :title="`为角色 ${currentRole?.roleName} 绑定菜单`" width="600px"
      @close="handleMenuBindDialogClose">
      <div class="menu-tree-container">
        <el-tree ref="menuTreeRef" :data="menuTreeData" node-key="id" :props="{
          children: 'children',
          label: 'menuName'
        }" highlight-current :expand-on-click-node="false">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span class="menu-name">{{ node.label }}</span>
              <el-checkbox v-model="data.isBand" @change="handleCheckboxChange(data)" />
            </span>
          </template>
        </el-tree>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="menuBindDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="bindMenus">绑定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.role-container {
  padding: 20px;
  height: calc(100vh - 40px);
  /* 减去padding */
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
  margin: 0;
  gap: 8px;
  max-height: calc(100vh - 40px);
}

h1 {
  color: #303133;
  margin-bottom: 16px;
  font-size: 24px;
  font-weight: 600;
}

p {
  color: #606266;
  margin-bottom: 24px;
  font-size: 14px;
}

/* 搜索栏样式 - 单行布局 */
.search-card {
  margin-bottom: 0;
  border-radius: 6px;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.08);
  flex-shrink: 0;
  overflow: visible;
  z-index: 20;
  position: relative;
  max-height: 80px;
  min-height: 80px;
  background: #fff;
}

.search-bar {
  padding: 12px 20px;
  position: relative;
  z-index: 15;
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 0;
  height: auto;
}

/* 搜索表单样式 - 单行布局 */
:deep(.search-form) {
  display: flex;
  flex-direction: column;
  gap: 0;
  width: 100%;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
  flex-wrap: nowrap;
  justify-content: space-between;
}

:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  display: flex;
  align-items: center;
  height: 36px;
  margin-right: 0;
  flex-shrink: 0;
}

:deep(.search-form .el-form-item__label) {
  line-height: 36px;
  padding-bottom: 0;
  font-size: 14px;
  margin-right: 8px;
  width: auto;
  display: flex;
  align-items: center;
  color: #606266;
  font-weight: 500;
  min-width: max-content;
  white-space: nowrap;
}

:deep(.search-form .el-input) {
  height: 36px;
  width: auto;
  flex-shrink: 0;
}

:deep(.search-form .el-input__inner) {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 100%;
  padding: 0 12px;
}

:deep(.search-form .el-select) {
  height: 36px;
  width: auto;
  flex-shrink: 0;
}

:deep(.search-form .el-select .el-input__inner) {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 100%;
  padding: 0 12px;
}

.search-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  height: 36px;
  margin-left: auto;
  flex-shrink: 0;
}

:deep(.search-actions .el-button) {
  height: 36px;
  padding: 0 16px;
  font-size: 14px;
  min-width: 70px;
}

/* 内联表单样式 */
:deep(.el-form--inline .el-form-item) {
  margin-right: 8px;
  margin-bottom: 0;
  display: inline-flex;
  align-items: center;
}

:deep(.el-form--inline .el-form-item__label) {
  line-height: 28px;
  padding-bottom: 0;
  font-size: 12px;
  margin-right: 4px;
  width: auto;
}

:deep(.el-form--inline .el-input) {
  height: 28px;
  width: auto;
}

:deep(.el-form--inline .el-input__inner) {
  height: 28px;
  line-height: 28px;
  font-size: 12px;
  width: 100%;
}

:deep(.el-form--inline .el-select) {
  height: 28px;
  width: auto;
}

:deep(.el-form--inline .el-select .el-input__inner) {
  height: 28px;
  line-height: 28px;
  font-size: 12px;
  width: 100%;
}

:deep(.el-form--inline .el-button) {
  height: 28px;
  padding: 0 10px;
  font-size: 12px;
  margin-left: 4px;
}

/* 表格容器样式 - 固定高度确保滚动条显示 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  position: relative;
  margin-top: 0;
  height: calc(100vh - 160px);
}

/* 表格包装器样式 - 固定高度和滚动设置 */
.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  position: relative;
  margin-top: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 表格样式 - 固定高度确保滚动条 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.el-table .el-table__header-wrapper) {
  flex-shrink: 0;
}

:deep(.el-table .el-table__body-wrapper) {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  max-height: 470px;
  /* 固定高度确保滚动条 */
}

/* 确保表格行高度合适 */
:deep(.el-table__row) {
  height: 48px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

/* 分页容器样式 - 固定在底部 */
.pagination-container {
  flex-shrink: 0;
  margin-top: 8px;
  padding: 12px 20px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.08);
  position: sticky;
  bottom: 0;
  z-index: 10;
  max-width: calc(100vw - 40px);
  box-sizing: border-box;
  margin-bottom: 0;
  height: auto;
  min-height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #ebeef5;
}

/* 表格标题样式 - 固定头部 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  background: inherit;
  z-index: 10;
}

/* 卡片内容区域样式 - 自适应高度 */
:deep(.el-card__body) {
  padding: 16px;
  margin-top: 0;
  height: auto;
  min-height: 0;
  overflow: visible;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

:deep(.el-table .el-button) {
  margin-right: 8px;
}

:deep(.el-table .el-button:last-child) {
  margin-right: 0;
}

/* 固定表格头部和操作列 */
:deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 10;
}

:deep(.el-table__fixed-header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 11;
}

:deep(.el-table__fixed-right) {
  position: sticky;
  right: 0;
  z-index: 10;
}

:deep(.el-table__fixed-left) {
  position: sticky;
  left: 0;
  z-index: 10;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 20px 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 10px 20px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 输入框样式 */
:deep(.el-input) {
  border-radius: 6px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
}

/* 卡片标题样式 */
:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
  font-weight: 600;
  color: #303133;
  border-radius: 12px 12px 0 0;
  position: sticky;
  top: 0;
  z-index: 10;
}

/* 菜单树容器样式 */
.menu-tree-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 12px;
}

:deep(.menu-tree-container .el-tree) {
  background: transparent;
}

:deep(.menu-tree-container .el-tree-node__content) {
  height: 36px;
  line-height: 36px;
}

:deep(.menu-tree-container .custom-tree-node) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 8px;
}

:deep(.menu-tree-container .el-checkbox) {
  margin-left: auto;
}
</style>
